import numpy as np

def getAngle(DataA, DataB):
    angle = 0
    countA_Beg = 0
    countB_Beg = 0
    # A = DataA[:,2]
    countA_End = len(DataA[:,2]) - 1
    countB_End = len(DataB[:,2]) - 1
    XA = DataA[:,0]
    XB = DataB[:,0]
    if DataA[0,2] > DataB[0,2]:
        while True:
            countB_Beg += 1
            if DataA[0,2] <= DataB[countB_Beg,2]:
                break
    else :
        while True:
            countA_Beg += 1
            if DataA[countA_Beg,2] >= DataB[0,2]:
                break
    if DataA[countA_End,2] > DataB[countB_End,2]:
        while True:
            countA_End -= 1
            if DataA[countA_End,2] <= DataB[countB_End,2]:
                break
    else :
        while True:
            countB_End -= 1
            if DataA[countA_End,2] >= DataB[countB_End,2]:
                break
    # 有效数据长度
    DataA_len = countA_End - countA_Beg + 1
    DataB_len = countB_End - countB_Beg + 1
    # 舍弃前20%
    DataA_de = round(DataA_len * 0.1)
    DataB_de = round(DataB_len * 0.1)

    DataA1 = XA[DataA_de+countA_Beg:countA_End]
    DataB1 = XB[DataB_de+countB_Beg:countB_End]
    # 计算绝对值和
    DataA1 = DataA1 - np.mean(DataA1)
    DataB1 = DataB1 - np.mean(DataB1)
    sumA = 0
    sumB = 0
    for i in range(0,len(DataA1)):
        sumA += np.abs(DataA1[i])
    sumA = sumA / len(DataA1)

    for i in range(0,len(DataB1)):
        sumB += np.abs(DataB1[i])
    sumB = sumB / len(DataB1)

    angle = np.arctan2(sumB, sumA) * 180.0 / np.pi
    return angle

import numpy as np
from scipy.fftpack import fft, ifft, fftshift
import matplotlib.pyplot as plt
from scipy import signal

def getL(data):
    dist = 10
    peaks = signal.find_peaks(data[:, 0], distance=dist)
    totalT = 0
    for i in  range(2, len(peaks[0])):
        totalT += data[peaks[0][i], 2] - data[peaks[0][i - 1], 2]
    T0 = totalT / (len(peaks[0]) - 2)

    f0 = 1 / T0
    L0 = (1 / (2 * np.pi * f0))**2 * 9.80665

    peaks = signal.find_peaks(-data[:, 0], distance=dist)
    totalT = 0
    for i in  range(2, len(peaks[0])):
        totalT += data[peaks[0][i], 2] - data[peaks[0][i - 1], 2]
    T1 = totalT / (len(peaks[0]) - 2)
    f1 = 1 / T1
    L1 = (1 / (2 * np.pi * f1))**2 * 9.80665

    f = 0
    minL = 0.4
    maxL = 1.6
    if L0 < maxL and L0 > minL and L1 < maxL and L1 > minL:
        f = (f0 + f1) /  2
    elif L0 < maxL and L0 > minL and (L1 > maxL or L1 < minL):
        f = f0
    elif L1 < maxL and L1 > minL and (L0 > maxL or L0 < minL):
        f = f1
    if f != 0:
        L = (1 / (2 * np.pi * f))**2 * 9.80665
        # print("L: " + str(L))
    else:
        # print("error")
        L = 0
    # peaklist = np.array(data[:, 0])[peaks[0][0:]]
    # plt.plot(data[peaks[0], 2], peaklist, '*')
    # plt.plot(data[:, 2], data[:, 0])
    # plt.show()
    return L